package com.ruix.app.ui.stratum.notice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.ruix.app.R;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ClasssDetailMapper;
import com.ruix.app.mapper.NoticeMapper;
import com.ruix.app.model.ClassDetail;
import com.ruix.app.model.Classes;
import com.ruix.app.model.Notice;
import com.ruix.app.model.Role;
import com.ruix.app.model.User;
import com.ruix.app.network.CacheObserver;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.adapter.NoticeListAdapter;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.RoleUtil;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/21.
 */

public class NotifyListActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, NoticeListAdapter.NoticeListListener{


    public static Intent newIntent(Context context, Classes classes,String from) {
        Intent intent = new Intent(context, NotifyListActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("classes", classes);
        bundle.putString("form",from);
        intent.putExtras(bundle);
        return intent;
    }

    private Classes currentClasses;
    private ListView noticesList;
    private TextView noMessageTip;
    private ImageView releaseNotice;
    private NoticeListAdapter adapter;
    private SpringView springView;
    private int LOAD_COUNT = 20;
    private SwipeRefreshLayout mRefreshLayout;
    private String from;

    private BroadcastReceiver myReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            if (RuiXConstant.NOTICE_UPDATE_NOTICE_LIST.equals(intent.getAction())){
                loadList(LOAD_COUNT, 0, false);
            }
        }

    };


    @Override
    protected int loadViewLayout() {
        return R.layout.activity_notify_list;
    }

    @Override
    protected void initView() {
        setTitle("通知");
        adapter = new NoticeListAdapter(this);

        noticesList = (ListView) findViewById(R.id.lv_notice_list);
        noMessageTip = (TextView) findViewById(R.id.tv_no_data_tip);
        releaseNotice = (ImageView) findViewById(R.id.iv_release_notice);//.setOnClickListener(this);
        noticesList.setAdapter(adapter);

        mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
        mRefreshLayout.setColorSchemeResources(R.color.bg_nav_default
                , R.color.bg_nav_yellow
                , R.color.bg_default
                , R.color.text_color_pink);

        springView = (SpringView) findViewById(R.id.spring_view);
        springView.setType(SpringView.Type.FOLLOW);
        springView.setGive(SpringView.Give.BOTTOM);
//        springView.setHeader(new DefaultHeader(this));
        springView.setFooter(new DefaultFooter(this));

        registerReceivers();
    }

    //不同的角色
    private void setReleaseNoticePermission(){
        String role = UserManager.getCurrentUser().getRole();
        if (RoleUtil.isAdviserOrHelperOrTeacher(role)) {
            releaseNotice.setVisibility(View.VISIBLE);
        } else {
            releaseNotice.setVisibility(View.GONE);
        }
    }


    @Override
    protected void initLocalData() {
        Intent intent = getIntent();
        if (intent != null) {
            currentClasses = (Classes) intent.getSerializableExtra("classes");
            from = intent.getStringExtra("form");
        }
        loadListWithCache();
        loadList(LOAD_COUNT, 0, true);
        if ("message".equals(from)){
            loadClassDetail();
        } else {
            setReleaseNoticePermission();
        }
    }

    @Override
    protected void initListener() {
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadList(LOAD_COUNT, 0, false);
            }
        });
        releaseNotice.setOnClickListener(this);
        noticesList.setOnItemClickListener(this);
        adapter.setListener(this);

        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadmore() {
                loadList(LOAD_COUNT, adapter.getCount(), false);
            }
        });
        noticesList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getFirstVisiblePosition() == 0 && view.getScaleY()==0) {
                        mRefreshLayout.setEnabled(true);
                    } else {
                        mRefreshLayout.setEnabled(false);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

//    private void initReleasViewWithUserRoleTpye() {
//        releaseNotice.setVisibility(View.VISIBLE);
//        // TODO: 2017/4/21
//    }

    private void showNoMessageTip() {
        noMessageTip.setVisibility(View.VISIBLE);
    }

    private void hideNoMessageTip() {
        noMessageTip.setVisibility(View.GONE);
    }

    private void loadListWithCache() {
        CacheFactory.loadNoticeList(currentClasses.getID(), new CacheObserver<ArrayList<Notice>>() {

            @Override
            public void onNext(ArrayList<Notice> value) {
                if (value != null && value.size() > 0) {
                    hideNoMessageTip();
                    adapter.replaceAll(value);
                }
            }

        });
    }

    private void loadList(int limit,final int offset, final boolean hasLoading) {
        if (hasLoading) {
            showLoading();
        }
        RequestFactory.noticeList(currentClasses.getID(), limit, offset, new NoticeMapper(), new RXObserver<ArrayList<Notice>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<Notice> value) {
                if (value != null && value.size() > 0) {
                    hideNoMessageTip();
                    if (offset > 0) {
                        adapter.addAll(value);
                    } else {
                        adapter.replaceAll(value);
                        CacheFactory.cacheNoticeList(currentClasses.getID(), value);
                    }
                } else {
                    if (hasLoading) {
                        showNoMessageTip();
                    } else {
                        showSuccessTip("没有更多通知");
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                if (hasLoading) {
                    dismissLoading();
                } else {
                    mRefreshLayout.setRefreshing(false);
                    springView.onFinishFreshAndLoad();
                }
                resolveException(e);
            }

            @Override
            public void onComplete() {
                if (hasLoading) {
                    dismissLoading();
                } else {
                    mRefreshLayout.setRefreshing(false);
                    springView.onFinishFreshAndLoad();
                }
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_release_notice:
                releaseNotice();
                break;
        }
    }

    private void releaseNotice() {
        this.startActivity(ReleaseNoiceActivity.newIntent(this, currentClasses));
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Notice notice = adapter.getItem(position);
        if (notice.isRichtext()){
            this.startActivity(NoticeRichtextDetailActivity.newIntent(this, notice));
        } else {
            this.startActivity(NoticeDetailActivity.newIntent(this, notice));
        }
        if (!notice.isReaded()){
            notice.setReaded(true);
        }
        adapter.notifyDataSetHasChanged();
    }

    @Override
    public void uncomfirmInfo(Notice item) {
        startActivity(ConfirmPersonActivity.newIntent(this, item));
    }


    private void registerReceivers(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(RuiXConstant.NOTICE_UPDATE_NOTICE_LIST);
        registerReceiver(myReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceivers();
//        EaseUI.getInstance().popActivity(this);
    }

    private void unregisterReceivers(){
        if (myReceiver != null){
            unregisterReceiver(myReceiver);
        }
    }

    private void loadClassDetail(){
        if (currentClasses == null){
            return;
        }
        RequestFactory.classDetail(currentClasses.getID(), new ClasssDetailMapper(currentClasses.getID()), new RXObserver<ClassDetail>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ClassDetail value) {
                if (value != null) {
                    setReleaseNoticePermission();
                }
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


}
